package com.loctek.importexport.util;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.InputStream;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

/**
 * Created by sihailin on 18/3/24.
 */

public class DomPersonService {
    /**
     * @param inStream
     * @return
     * @throws Exception
     */
    public static String changeColor(InputStream inStream, String changeId, String color)
            throws Exception {

        /**
         * 文檔的解析
         */
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(inStream);
        /**
         * 操作對象樹
         */
        Element root = document.getDocumentElement();//返回文檔的根元素
        NodeList pathNodes = root.getElementsByTagName("path");
        boolean change = false;
        for (int i = 0; i < pathNodes.getLength(); i++) {
            Element pathElement = (Element) pathNodes.item(i);
            String id = pathElement.getAttribute("id");
            if (TextUtils.equals(changeId, id)) {
                Log.v("changeColor", "id->>" + id);
                pathElement.setAttribute("fill", color);
                change = true;
                break;
            }
        }
        if (!change) {
            Log.e("changeColor", "没有找到ID");
            inStream.close();
            return null;
        }

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source xmlSource = new DOMSource(document);

        String SDCardRoot = Environment.getExternalStorageDirectory() + File.separator;
        String fileName = new Date().getTime() + "_temp.svg";
        File outFile = new File(SDCardRoot + "Damei" + File.separator + fileName);
        Result outputTarget = new StreamResult(outFile);//xm文件所在位置
        transformer.transform(xmlSource, outputTarget);//提交覆盖原来的xml

        inStream.close();
        return outFile.getAbsolutePath();
    }
}
